var investigationFileCategory = ['', '现场照', '承债证据', '资产查询证据'],
    host = $('#host').val() + '/', //域名
    ajaxUrl = $('#file_get_list').val(), //分页列表
    deleteUrl = $('#file_delete').val(),
    url = $('#upload_url').val(),//上传地址
    downloadUrl = $('#file_download').val(),
    updateUrl = $('#file_update').val(),
    project_id = $('#project_id').val(), //项目id
    state = 0, //显示红旗，1显示，2不显示，默认0
    uploadFileName = '', //上传文件名
    upload_state = true; //是否上传

$(function () {
    //浏览图片
    /*$('#fuJian').find('.file_list').on('click', '.show_image', function () {
     var src = $(this).data('src');
     $('.show_image').find('.modal-body').find('img').attr('src', '/uploads/investigation-file/' + src);
     $("#show_image").trigger("click");
     })
     //模态框确认
     $('.show_image').on('click', '.image_show_config', function () {
     $(this).next().trigger('click');
     })*/

    //清空上传记录
    $('.upload-file').click(function () {
        $('.upload_img_click').prevAll().remove();
        $('.errorText').empty();
    })

    //上传图片
    $('#fuJian').find('.fileBox').on('click', '.uploadImg', function () {
        //$('#file-1').trigger('click');
        if (upload_state === true) {
            $('#uplaodImages').trigger('click');
        }
    });

    //上传图片
    $('#fuJian').on('change', '#uplaodImages', function () {
        upload_state = false;
        var category = $('#category_upload').val();
        if (category == 0) {
            layer.msg('请选择所属模块');
            return false;
        }
        url = url + '?project_id=' + project_id + '&category=' + category;
        var option = {
            url: url,
            type: 'POST',
            dataType: 'json',
            headers: {"ClientCallMode": "ajax"}, //添加请求头部
            //target:target, //服务器返回的响应数据显示在元素(Id)号确定
            //clearForm:true, //提交成功后是否清空表单中的字段值
            //restForm:true, //提交成功后是否重置表单中的字段值,即恢复到页面加载时的状态
            // timeout:6000, //设置请求时间，超过该时间后，自动退出请求，单位(毫秒)。
            beforeSubmit: function (files) {
                var html = '', html2 = '', files_array = [];

                $.each(files, function (i, n) {
                    var name = n.value.name;
                    files_array.push(name);
                    html += '<li class="pull-left image_uploading">' +
                        '<img src="' + host + 'image/defaultPage/uploading.png" title="' + name + '" alt="' + name + '" />' +
                        '<p class="txt-cut" title="' + name + '">' + name + '</p></li>';
                    html2 += '<div class="image_uploading">' + name + ' <span style="color: #F8FA00;">上传中</span></div>';
                })

                $('#files_name').val(files_array.join('%##%'));
                $('.upload_img_click').before(html);
                $('.errorText').append(html2);

                //return false;

            },
            success: function (data) {
                upload_state = true;
                var files = $('#files_name').val().split('%##%');
                $('.fileBox').find('.image_uploading').remove();
                if (data.code == 200) {
                    var html1 = '', html2 = '';
                    $.each(files, function (i, n) {
                        var name = n;
                        html1 += '<li class="pull-left ">' +
                            '<img src="' + host + 'image/defaultPage/uploadSuccess.png" title="' + name + '" alt="' + name + '" />' +
                            '<p class="txt-cut" title="' + name + '">' + name + '</p></li>';
                        html2 += '<div>' + name + ' <span style="color: #F8FA00;">上传成功</span></div>';
                    })
                    $('.upload_img_click').before(html1);
                    $('.errorText').append(html2);

                    /**********  列表及分页  **********/
                        //列表
                    var html = getHtml(data.data.res.list, 1);
                    $('.page_list_prev').nextAll().remove();
                    $('.page_list_prev').after(html);
                    $('#page_list').children().remove();

                    //分页及总数量
                    if (data.data.res.count > 0) {
                        $('#page_list').html(data.data.res.pager);
                        $('.pagingBox').find('.totalSize').text(data.data.res.count);
                    } else {
                        $('.pagingBox').find('.totalSize').text(0);
                    }
                    //当前页
                    $('#current_page').val(data.data.res.page);

                } else if (data.code == 400) {
                    upload_state = true;
                    if (data.data.res.length > 0) {
                        var html1 = '', html2 = '';
                        $.each(data.data.res, function (i, n) {
                            html1 += '<li class="pull-left error-Img">' +
                                '<p class="clearfix"></p><img src="' + host + 'image/officeHall/uploadAssetPackage/closImg.png" ' +
                                'data-filename="' + n.fileName + '"' + 'class="pull-left closeImg" alt="点击关闭"  title="点击关闭"/></p>' +
                                '<span class="pull-left txt-cut">' + n.olderFileName + '</span></li>';
                            html2 += '<div class="defeatedWaring" data-filename="' + n.olderFileName + '" data-state="error"><img src="' + host + 'image/officeHall/uploadAssetPackage/defeatedWaring.png' + '" class="pull-left errorImg"/>' +
                                n.olderFileName + '<span> 上传失败:' + data.message + '</span></div>';
                        });
                        $('.upload_img_click').before(html1);
                        $('.errorText').append(html2);
                    } else {
                        var html2 = '';
                        $.each(files, function (i, n) {
                            var name = n;
                            html2 = '<div class="defeatedWaring" data-filename="' + name + '" data-state="error">' + name + '<span> 上传失败：' + data.message + '</span></div>';
                        })
                        $('.errorText').append(html2);
                    }
                }
            },
            error: function (data) {
                upload_state = true;
                $('.fileBox').find('.image_uploading').remove();
                layer.msg('请选择图片');
            }
        };
        $("form.uploads").ajaxSubmit(option);
    })

    //----------------------------------------- 删除上传失败图片 ---------------------------------------
    //$('.fileBox p.clearfix').on('click', '.closImg', function (event) {
    $('.fileBox').on('click', '.closeImg', function (event) {
        var obj = $(this),
            fileName = $(this).data('filename'),
            deleteUrl = $('#file_delete_url').val(),
            param = {};
        param.project_id = project_id;
        param.file_name = fileName;
        param.type = 2;

        $.ajax({
            url: deleteUrl,
            type: 'POST',
            async: true,
            data: param,
            //timeout: 5000,    //超时时间
            dataType: 'json',
            success: function (data, textStatus, jqXHR) {
                if (data.code == 200) {
                    layer.msg(data.message);
                    obj.parent().remove();
                    $('.defeatedWaring').each(function () {
                        var name = $(this).data('state');
                        if (name == 'error') {
                            $(this).remove();
                        }
                    })
                } else if (data.code == 400) {
                    layer.msg(data.message);
                }
            },
            error: function (xhr, textStatus) {
                layer.msg('系统错误');
            }
        })
    })
})

//切换红旗
$('#fuJian').on('click', '.redFlag', function () {
    //$(this).toggleClass('redFlag2');
    var id = $(this).data('id'),
        type = $(this).hasClass('redFlag2'),
        obj = $(this),
        param = {};
    if (type) {
        param.state = 1;
    } else {
        param.state = 2;
    }

    param.id = id;
    param.project_id = project_id;

    $.ajax({
        url: updateUrl,
        type: 'POST',
        async: true,
        data: param,
        //timeout: 5000,    //超时时间
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            console.log(data);
            if (data.code == 200) {
                if (type) {
                    obj.removeClass('redFlag2');
                } else {
                    obj.addClass('redFlag2');
                }
            }
        },
        error: function (xhr, textStatus) {
            layer.msg('系统错误');
        }
    })
})

//编辑
$('.jinTiao91 form table').on('change', '.table-text', function () {
    var value = $(this).val(),
        title = $(this).data('title'),
        id = $(this).parent().parent().parent().data('id');
    if (title != value) {
        var param = {};
        param.title = value;
        param.project_id = project_id;
        param.id = id;

        editFile(updateUrl, param);
    }
})
$('.jinTiao91 form table').on('change', '.category', function () {
    var category = $(this).val(),
        id = $(this).parent().parent().data('id'),
        param = {};
    param.category = category;
    param.project_id = project_id;
    param.id = id;
    editFile(updateUrl, param);
})

//-----------------------------------------—— 分页列表 start ----------------------------------------
//显示关闭红旗附件
$('.onOff').on('click', function () {
    $(this).toggleClass("onInoff");
    if ($(this).hasClass('onInoff')) {
        state = 1;
        var category = $('.category_list').val(),
            page = parseInt($('#current_page').val(), 10),
            //pageSize = parseInt($('#list .number').text(), 10),
            pageSize = 10,
            param = {};

        param.project_id = project_id;
        param.state = state;
        param.category = category;
        param.pageSize = pageSize;
        getPageList(param, ajaxUrl, page);

        //$('.redFlag2').parent().parent().hide();
    } else {
        state = 0;
        var category = $('.category_list').val(),
            page = parseInt($('#current_page').val(), 10),
            //pageSize = parseInt($('#list .number').text(), 10),
            pageSize = 10,
            param = {};

        param.project_id = project_id;
        param.state = state;
        param.category = category;
        param.pageSize = pageSize;
        getPageList(param, ajaxUrl, page);

        //$('.redFlag2').parent().parent().show();
    }
})

//选择模块
$('.category_list').change(function () {
    var page = parseInt($('#current_page').val(), 10),
        //pageSize = parseInt($('#list .number').text(), 10),
        pageSize = 10,
        param = {};

    param.project_id = project_id;
    param.state = state;
    param.category = $(this).val();
    param.pageSize = pageSize;
    param.page = page;

    getPageList(param, ajaxUrl, page);
});

//选择页面
$("body").delegate("#page_list .pagination a", "click", function (e) {
    e.preventDefault();

    var cs = $(this).attr('href').split('?');
    //var cs = $(this).attr('href');
    //var urlParam = cs.substring(cs.indexOf('&')+1).split('&');
    //var pages = urlParam[1].split('=');

    var category = $('.category_list').val();
    //var pageSize = parseInt($('#list .number').text(), 10);
    var pageSize = 10,
        ajaxUrl = $('#file_get_list').val() + '?' + cs[1];

    var param = {};
    param.project_id = project_id;
    param.state = state;
    param.category = category;
    param.pageSize = pageSize;


    console.log(param)
    console.log(ajaxUrl)

    getPageList(param, ajaxUrl, '');
});

//选择每页条数
$('#list .pageTotalBox').on('click', 'li', function () {
    var category = $('.category_list').val(),
        page = parseInt($('#current_page').val(), 10),
        //pageSize = parseInt($('#list .number').text(), 10),
        pageSize = 10,
        param = {};

    param.project_id = project_id;
    param.state = state;
    param.category = category;
    param.pageSize = pageSize;

    getPageList(param, ajaxUrl, page);
});
//-----------------------------------------—— 分页列表 end ----------------------------------------


/*$("#file-1").fileinput({
 language: 'zh', //设置语言
 uploadUrl: url,
 uploadExtraData: {"project_id": project_id, 'category': $('#category_upload').val()},
 //allowedFileExtensions: ["jpg", "jpeg", "png", "gif"],
 browseClass: "btn btn-primary btn-block",
 showCaption: false,
 showRemove: false,
 showUpload: false
 }).on('fileselect', function (event, numFiles, label) {
 $('#file-1').fileinput('upload');
 }).on("filebatchselected", function (event, files) {
 if (files.length > 0) {
 uploadFileName = files['0']['name'];
 }

 }).on('filepreupload', function (event, data, previewId, index) {
 var name = data.files[index].name;
 var html = '<li class="pull-left image_uploading">' +
 '<img src="' + host + 'image/officeHall/uploadAssetPackage/uploading.png" title="' + name + '" alt="' + name + '" />' +
 '<p>' + name + '</p></li>';
 var html2 = '<div class="image_uploading">' + name + ' <span style="color: #F8FA00;">上传中</span></div>';

 $('.upload_img_click').before(html);
 $('.errorText').append(html2);

 }).on("fileuploaded", function (event, data, previewId, index) {
 $('.fileBox').find('.image_uploading').remove();

 var param = data.response;
 if (param.code == 200) {
 var html = '<li class="pull-left ">' +
 '<img src="' + host + 'image/officeHall/uploadAssetPackage/uploadSuccessfully.png" title="' + uploadFileName + '" alt="' + uploadFileName + '" />' +
 '<span>' + uploadFileName + '</span></li>';
 var html2 = '<div>' + uploadFileName + ' <span style="color: green;">上传成功</span></div>';

 $('.upload_img_click').before(html);
 $('.errorText').append(html2);

 } else if (param.code == 400) {
 if (param.data.res.length > 0) {
 var html1 = '', html2 = '';
 $.each(param.data.res, function (i, n) {
 html1 += '<li class="pull-left error-Img">' +
 '<p class="clearfix"></p><img src="' + host + 'image/officeHall/uploadAssetPackage/closImg.png" ' +
 'data-filename="' + n.fileName + '"' + 'class="pull-left closeImg" alt="点击关闭"  title="点击关闭"/></p>' +
 '<span class="pull-left">' + n.olderFileName + '</span></li>';

 html2 += '<div class="defeatedWaring" data-filename="' + n.olderFileName + '"><img src="' + host + 'image/officeHall/uploadAssetPackage/defeatedWaring.png' + '" class="pull-left errorImg"/>' +
 n.olderFileName + '<span> 上传失败:' + param.message + '</span></div>';
 });
 $('.upload_img_click').before(html1);
 $('.errorText').append(html2);
 } else {
 var html2 = '<div class="defeatedWaring" data-filename="' + uploadFileName + '">' + uploadFileName + '<span> 上传失败：' + param.message + '</span></div>';
 $('.errorText').append(html2);
 }
 $('#file-1').fileinput('reset');
 }

 }).on('fileerror', function (event, data, msg) {
 $('.fileBox').find('.image_uploading').remove();
 $('#file-1').fileinput('reset');
 layer.alert('请选择图片');
 });*/


/**
 * 分页列表
 * @param param 请求数据
 * @param url 请求地址
 * @param page 当前页
 */
function getPageList(param, url, page) {
    $.ajax({
        type: "GET",
        url: url,
        data: param,
        datatype: "json",
        //成功返回之后调用的函数
        success: function (data) {
            if (data.code == 200) {
                layer.msg('加载完成');
                //分页
                $('#page_list').children().remove();

                if (data.data.res.count > 0) {
                    $('#page_list').html(data.data.res.pager);
                    $('.pagingBox').find('.totalSize').text(data.data.res.count);
                } else {
                    $('.pagingBox').find('.totalSize').text(0);
                }

                //列表数据e
                $('.page_list_prev').nextAll().remove();
                var html = getHtml(data.data.res.list, data.data.res.page);
                $('.page_list_prev').after(html);
                $('#current_page').val(data.data.res.page);
            }
        },
        //调用出错执行的函数
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg('系统错误');
        }
    });
}

function getHtml(data, current_page) {
    var html = '';
    var j = 10 * (current_page-1);
    $.each(data, function (i, n) {
        html += '<tr data-id="' + n.id + '">' +
            '<td> <input type="checkbox" name="" id="' + n.id + '" value="'+ n.id +'"/> </td>' +
            //'<td>' + n.id + '</td>';
            '<td>' + (++j) + '</td>';
        if (n.state == 1) {
            html += '<td> <span class="redFlag" data-id="' + n.id + '" title="单击改变红旗"></span> <span class="tableSpan">';
        } else {
            html += '<td> <span class="redFlag redFlag2" data-id="' + n.id + '" title="单击改变红旗"></span> <span class="tableSpan">';
        }

        html += '<input type="text" class="table-text" data-title="' + n.title + '" readonly="readonly" value="' + n.title + '"/> </span>' +
            '</td>' +
            '<td class="selectBox">' +
            '<select name="category" class="select-sanjiao" id="table-select" disabled="disabled">';
        if (n.category > 0) {
            $.each(investigationFileCategory, function (i, v) {
                if (i > 0) {
                    if (i == n.category) {
                        html += '<option value="' + n.category + '" selected>' + v + '</option>';
                    } else {
                        html += '<option value="' + n.category + '" >' + v + '</option>';
                    }
                }
            })
        } else {
            html += '<option value="0" selected>全部</option>';
        }

        html += '</select>' +
            '</td>' +
            '<td> <span>' + n.size + '</span> </td>' +
            '<td class="uploaded_by"> <input type="text" readonly value="' + n.uploaded_by + '"/> </td>' +
            '<td> <input type="text" readonly value="' + n.created_at + '"/> </td>' +
            '<td>' +
            '<span><a href="' + downloadUrl + '?project_id=' + project_id + '&id=' + n.id + '"> ' +
            '<img  src="' + host + 'image/projectDetails/download.png" alt="下载" title="下载" data-url="' + downloadUrl + '" data-id="' + n.id + '" /> ' +
            '</a></span >' +
            '<span > <img class="delete_file"  src="' + host + 'image/projectDetails/recovery.png" class="remove" alt="删除" title="删除" ' +
            //'data-toggle="modal" ' + 'data-target="#deleModal" ' +
            'data-url="' + deleteUrl + '" data-id="' + n.id + '" /> </span>' +
            '<span><a href="/uploads/investigation-file/' + n.file_name + '"  target="_blank"> <img  src="' + host + 'image/projectDetails/eye.png" class="show_image" data-src="' + n.file_name + '" alt="查看" title="查看" /></a> </span>' +
            '<span> <img  src="' + host + 'image/projectDetails/tableEdit.png" class="tableEdit edit-tab"alt="编辑" title="编辑" /> </span>' +
            '</td> </tr>';
    });

    return html;
}

/**
 * 编辑
 * @param url
 * @param param
 */
function editFile(url, param) {
    $.ajax({
        url: url,
        type: 'POST',
        async: true,
        data: param,
        //timeout: 5000,    //超时时间
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            if (data.code == 200) {
                layer.msg('修改成功');
            } else if (data.code == 400) {
                layer.msg(data.message);
            }
        },
        error: function (xhr, textStatus) {
            layer.msg('系统错误');
        }
    })
}


/**
 * 批量下载
 */
function downloads() {
    var obj = $('.page_list_prev').nextAll('tr').find('td:first-child>input[type=checkbox]:checked');
    if (obj.length) {
        var downloadsUrl = $('#file_downloads').val(),
        ids_arr = [],
        ids = '',
        orders_arr = [],
        orders = '';
        $.each( obj, function(i, n){
            orders_arr.push($(this).parent().next().text())
            ids_arr.push($(this).val())
        });

        ids = ids_arr.join(',');
        orders = orders_arr.join(',');

        //window.open(downloadsUrl + '?project_id='+ project_id + '&ids=' + ids + '&orders=' + orders);
        window.location.href = downloadsUrl + '?project_id='+ project_id + '&ids=' + ids + '&orders=' + orders;
    } else {
        layer.msg('请选择下载的附件');
    }
}


/**
 * 查找关联历史档案
 */
function searchHistory() {
    layer.msg('正在开发中...');
}
